package com.qd.p2p.web.action.additional;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.AdditionalUserDrawLotteryService;
import com.qdlc.p2p.biz.service.LotteryRecordService;
import com.qdlc.p2p.biz.service.UserSignService;
import com.qdlc.p2p.biz.service.lottery.AbstractDrawLotteryService;
import com.qdlc.p2p.biz.service.lottery.LotteryService;
import com.qdlc.p2p.biz.service.lottery.LotteryTaskService;
import com.qdlc.p2p.biz.util.ActivityTools;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.biz.zdata.LotteryResult;
import com.qdlc.p2p.common.constant.LotteryCategory;
import com.qdlc.p2p.common.core.redis.JedisCache;
import com.qdlc.p2p.common.core.redis.JedisCacheFactory;
import com.qdlc.p2p.common.core.redis.JedisCallable;
import com.qdlc.p2p.common.enums.EnumActicityPlanNid;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dao.LotteryDao;
import com.qdlc.p2p.dal.dto.AdditionalUserDrawLottery;
import com.qdlc.p2p.dal.dto.Lottery;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserSign;
import com.qdlc.p2p.dal.model.ScoreLotteryRecordModel;

/**
 * 签到抽奖
 */
public class CountLotteryAction extends BaseAction<ScoreLotteryRecordModel> implements ModelDriven<ScoreLotteryRecordModel> {

    @Resource
    private LotteryRecordService lotteryRecordService;
    @Resource
    private LotteryService lotteryService;
    @Resource
    private LotteryTaskService lotteryTaskService;
    @Resource
    private UserSignService userSignService;
    @Resource
    private AbstractDrawLotteryService countDrawLotteryService;
    @Resource
    private AdditionalUserDrawLotteryService additionalUserDrawLotteryService;

    private Map<String, Object> data;

    /**
     * 签到抽奖页面
     *
     * @return
     */
    @Action(value = "/member/signLottery")
    public String signLottery() {
        saveToken("signLottery");
        return "signLottery";
    }

    /**
     * ----------------------签到抽奖-----------------------------
     * 签到抽奖记录
     *
     * @return
     * @throws IOException
     */
    @Action(value = "/member/signLotteryList", interceptorRefs = {@InterceptorRef("ajaxSafe"), @InterceptorRef("globalStack")})
    public void signLotteryList() throws IOException {
        JedisCache<List> jedisCache = JedisCacheFactory.newInstance(List.class);
        List list =  jedisCache.get("lotteryRecordList", 1, TimeUnit.MINUTES, new JedisCallable<List>() {
            public List  call() {
                return  lotteryRecordService.getNewList(LotteryCategory.SIGN.getCategory());
            }
        });
        data = new HashMap<String, Object>();
        data.put("data", list);
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * 签到抽奖
     *
     * @return
     * @throws IOException
     */
    @Action("/member/doSignLottery")
    public void doSignLottery() throws IOException {
        if (getSessionUser() == null) {
            throw new UserException("请登录", BusinessException.TYPE_JSON);
        }
        model.setUser(getSessionUser());
        data = new HashMap<String, Object>();
        //校验token
        try {
            checkLotteryToken("signLottery");
        } catch (BusinessException e) {
            throw new BusinessException(e.getMessage(), BusinessException.TYPE_JSON);
        }
        // 签到抽奖
        LotteryResult lottery = countDrawLotteryService.process(getSessionUser(), LotteryCategory.SIGN.getCategory());
        // 转盘对应角度设置。
        List<Lottery> lotteryConfig = lotteryService.getLotteryByCategory(LotteryCategory.SIGN.getCategory());
        int size = lotteryConfig.size();
        int angle = (180 / size) * (lottery.getPos() * 2 - 1);
        lottery.setPos(angle);
        data.put("result", lottery);
        saveToken("signLottery");
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * 抽奖奖品列表
     */
    @Action("/member/signLotteryAwardList")
    public void signLotteryAwardList() throws IOException {
        LotteryDao lotteryDao = (LotteryDao) BeanUtil.getBean("lotteryDao");
        QueryParam param = QueryParam.getInstance();
        param.addParam("category", LotteryCategory.SIGN.getCategory());
        List<Lottery> lotteryAwardList = lotteryDao.findByCriteria(param, 0, 3);
        if (null != lotteryAwardList) {
            data = new HashMap<String, Object>();
            data.put("data", lotteryAwardList);
            printWebJson(getStringOfJpaObj(data));
        }
    }

    /**
     * 用户签到
     *
     * @return
     */
    @Action("/user/doSign")
    public void doSign() throws Exception {
        User user = getSessionUser();
        if (user  == null) {
            throw new UserException("请登录", BusinessException.TYPE_JSON);
        }
        data = new HashMap<String, Object>();
        UserSign userSign = userSignService.findLastRecord(user.getUserId());
        // 用户今天签到过了
        if (userSign != null && ActivityTools.getCurrentDate().equals(ActivityTools.format(userSign.getSignTime()))) {
            data.put("result", false);
            printWebJson(getStringOfJpaObj(data));
            return;
        }
        // 用户昨天签到
        if (userSign != null && ActivityTools.getPreDate().equals(ActivityTools.format(userSign.getSignTime()))) {
            //赠送签到活动对应规则
            lotteryTaskService.recordUserSign(user, userSign.getSignDayCount() + 1,getRequestIp());
            data.put("result", true);
        } else {
            //赠送签到活动对应规则
            lotteryTaskService.recordUserSign(user, 1,getRequestIp());
            data.put("result", true);
        }
        // 活动方案执行
        try {
            lotteryTaskService.signActivityPlan(user.getUserId(), EnumActicityPlanNid.SIGN.getValue(),user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * 判断用户是否可以签到
     *
     * @return
     */
    @Action("/user/getSignStatus")
    public void getSignStatus() throws IOException {
        data = new HashMap<String, Object>();
        User user = getSessionUser();
        if (user == null) {
            data.put("signStatus", -1);
            printWebJson(getStringOfJpaObj(data));
            return;
        }
        UserSign userSign = userSignService.findLastRecord(user.getUserId());
        if(userSign == null || !ActivityTools.getCurrentDate().equals(ActivityTools.format(userSign.getSignTime()))) {
            // 签到抽奖状态：0未签到，1已签到未抽奖，2已抽奖
            data.put("signStatus", 0);
        } else {
            // 今天已经签到：再判断是否有抽奖机会;
            AdditionalUserDrawLottery additionalUserDrawLottery = additionalUserDrawLotteryService.getValidDrawLotteryByUserId(user.getUserId());
            int signStatus = additionalUserDrawLottery.getId() != 0? 1:2;
            data.put("signStatus", signStatus);
        }
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * 校验token
     * @param key
     */
    private void checkLotteryToken(String key) {
        String tokenValue = StringUtil.isNull((String) session.get(key));
        if (StringUtil.isBlank(tokenValue)) {
            throw new BusinessException("会话Token未设定，请刷新页面后重试", 2);
        } else if (StringUtil.isNotBlank(tokenValue)) {
            session.remove(key);
        } else {
            throw new BusinessException("请勿重复提交。", 2);
        }
    }

    /**
     * 抽奖现金代收容错地址
     *//*
    @Action(NotifyUrl.RE_CASH_LOTTERY_REQ_URL)
    public void cashLotteryExchangeCollect() throws IOException {
        String token = paramString("token");
        if (NotifyUrl.RE_CALL_TOKEN.equalsIgnoreCase(token)) {
            throw new RedEnvelopeException("补单令牌不正确,无法操作!", RedEnvelopeException.TYPE_JSON);
        }

        long userId = paramLong("userId");
        byte lotteryType = (byte)paramInt("lotteryType");
        double amount = paramDouble("money");
        User exchangeUser = userDao.getUserById(userId);

        if (userId == 0||lotteryType==0||amount==0) {
            throw new RedEnvelopeException("补单参数有误!", RedEnvelopeException.TYPE_JSON);
        }

        try {
            TppTradeLog tppTradeLog =  lotteryTaskService.createCollectOrder(exchangeUser,lotteryType,amount);
            lotteryTaskService.giveCash(exchangeUser,amount, lotteryType);

            } catch (Exception e) {
                throw new RedEnvelopeException("补单失败!", RedEnvelopeException.TYPE_JSON);
        }
    }*/

   /* *//**
     * 抽奖现金代付补单地址
     *//*
    @Action(NotifyUrl.RE_CASH_LOTTERY_PAY_REQ_URL)
    public void cashLotteryExchangePAY() throws IOException {
        String token = paramString("token");
        if (NotifyUrl.RE_CALL_TOKEN.equalsIgnoreCase(token)) {
            throw new RedEnvelopeException("补单令牌不正确,无法操作!", RedEnvelopeException.TYPE_JSON);
        }

        // 订单号
        String orderNo = paramString("order_no");
        if (StringUtil.isEmpty(orderNo)) {
            throw new RedEnvelopeException("代收的订单不存在!", RedEnvelopeException.TYPE_JSON);
        }

        // 根据订单号 查询代收Log
        TppTradeLog tppTradeLog = tppTradeLogDao.find(orderNo);

        // 生成新的订单
        tppTradeLog = lotteryTaskService.createPayOrder(tppTradeLog);
        // 发起代付
        lotteryTaskService.cashLotteryExchangeForPay(tppTradeLog);
    }*/
}
